package com.boot2.core.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;

/**
 * @author zhangweilin
 * @ClassName: Base64StringUtil
 * @description: base 64加密,纯String的转换
 * @date 2017年12月22日 下午3:53:31
 */
public class Base64StringUtil {
    // 加密
    public static String getBase64(String str) {
        byte[] b = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return getBase64(b);
    }

    public static String getBase64(byte[] b) {
        String s = null;
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    // 解密
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String str = "1234657964";
        String str2 = Base64StringUtil.getBase64(str);
        System.out.println("str2: " + str2);
        String str3 = Base64StringUtil.getFromBase64(str2);
        System.out.println("str3: " + str3);
    }
}